<template>
  <div class="user-container">
    <h1>客户管理</h1>
    <div class="operation-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入客户名称或地址关键词搜索"
        style="width: 300px;"
        clearable
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="success" @click="handleAdd">新增客户</el-button>
    </div>
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 15px;"
    >
      <el-table-column prop="userId" label="ID" width="80" />
      <el-table-column prop="userName" label="客户名称" />
      <el-table-column prop="userType" label="客户类型" />
      <el-table-column prop="userAddress" label="客户地址" />
      <el-table-column prop="userPhone" label="客户电话" />
      <el-table-column prop="readyAmount" label="预存余额" />
      <el-table-column prop="costAmount" label="消费总额" />
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column prop="status" label="状态" :formatter="formatStatus" />
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.userId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区 -->
    <div class="pagination-bar" v-if="total > 0">
      <el-pagination
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
      ></el-pagination>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form
        :model="formData"
        ref="formRef"
        label-width="120px"
      >
        <el-form-item label="客户名称" prop="userName" :rules="{ required: true, message: '请输入客户名称', trigger: 'blur' }">
          <el-input v-model="formData.userName" placeholder="请输入客户名称"></el-input>
        </el-form-item>
        <el-form-item label="客户类型" prop="userType" :rules="{ required: true, message: '请选择客户类型', trigger: 'change' }">
          <el-select v-model="formData.userType" placeholder="请选择客户类型" disabled>
            <el-option label="公客" value="公客"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户地址" prop="userAddress" :rules="{ required: true, message: '请输入客户地址', trigger: 'blur' }">
          <el-input v-model="formData.userAddress" placeholder="请输入客户地址"></el-input>
        </el-form-item>
        <!-- 客户电话添加11位数字验证 -->
        <el-form-item
          label="客户电话"
          prop="userPhone"
          :rules="[
            { required: true, message: '请输入客户电话', trigger: 'blur' },
            { min: 11, max: 11, message: '请输入11位电话号码', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
          ]"
        >
          <el-input
            v-model="formData.userPhone"
            placeholder="请输入11位手机号码"
            type="tel"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="预存余额" prop="readyAmount" :rules="{ required: true, message: '请输入预存余额', trigger: 'blur' }">
          <el-input v-model="formData.readyAmount" type="number" placeholder="请输入预存余额"></el-input>
        </el-form-item>
        <el-form-item label="消费总额" prop="costAmount" :rules="{ required: true, message: '请输入消费总额', trigger: 'blur' }">
          <el-input v-model="formData.costAmount" type="number" placeholder="请输入消费总额"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status" :rules="{ required: true, message: '请选择状态', trigger: 'change' }">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import {
  getpublicuserPageAPI,
  adduserAPI,
  updateuserAPI,
  deleteuserAPI,
  searchuserAPI
} from '@/apis/userAPI'; // 根据实际路径调整

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchKeyword = ref('');

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('新增客户');
const formRef = ref(null);
const formData = reactive({
  userId: null,
  userName: '',
  userType: '公客',
  userAddress: '',
  industryManager: '',
  userIndustry: '',
  communityManager: '',
  userPhone: '',
  readyAmount: 0,
  costAmount: 0,
  status: '1'
});

// 初始化页面加载数据
onMounted(() => {
  fetchUserList();
});

// 获取列表数据
const fetchUserList = async () => {
  try {
    const response = await getpublicuserPageAPI(currentPage.value);
    console.log(response);

    if (response.code === 0) {
      // 确保状态值为字符串类型，与表单保持一致
      tableData.value = response.data.records.map(item => ({
        ...item,
        status: item.status.toString()
      }));
      total.value = response.data.total;
      pageSize.value = response.data.size;
    }
  } catch (error) {
    console.error('获取客户列表失败:', error);
    ElMessage.error('获取客户列表失败');
  }
};

// 搜索功能
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    // 关键词为空时加载默认列表
    fetchUserList();
    return;
  }

  try {
    const response = await searchuserAPI(searchKeyword.value);
    if (response.code === 0) {
      // 确保状态值为字符串类型，与表单保持一致
      tableData.value = response.data.map(item => ({
        ...item,
        status: item.status.toString()
      }));
      total.value = response.data.length;
    }
  } catch (error) {
    console.error('搜索客户失败:', error);
    ElMessage.error('搜索客户失败');
  }
};

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchUserList();
};

// 状态格式化
const formatStatus = (row) => {
  return row.status === '1' ? '启用' : '禁用';
};

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增客户';
  // 重置表单
  formData.userId = null;
  formData.userName = '';
  formData.userType = '公客';
  formData.userAddress = '';
  formData.userPhone = '';
  formData.industryManager = '';
  formData.userIndustry = '';
  formData.communityManager = '';
  formData.readyAmount = 0;
  formData.costAmount = 0;
  formData.status = '1';
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑客户';
  // 复制行数据到表单，确保状态值为字符串
  formData.userId = row.userId;
  formData.userName = row.userName;
  formData.userType = '公客';
  formData.userAddress = row.userAddress;
  formData.userPhone = row.userPhone;
  formData.industryManager = row.industryManager;
  formData.userIndustry = row.userIndustry;
  formData.communityManager = row.communityManager;
  formData.readyAmount = row.readyAmount;
  formData.costAmount = row.costAmount;
  formData.status = row.status.toString();
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  const form = formRef.value;
  if (!form) return;

  try {
    await form.validate();

    // 准备提交数据，将状态转换为数字
    const submitData = {
      ...formData,
      status: parseInt(formData.status)
    };

    if (formData.userId) {
      // 编辑操作
      const response = await updateuserAPI(submitData);
      if (response.code === 0) {
        dialogVisible.value = false;
        fetchUserList();
        ElMessage.success('修改客户成功');
      }
    } else {
      // 新增操作
      const response = await adduserAPI(submitData);
      if (response.code === 0) {
        dialogVisible.value = false;
        fetchUserList();
        ElMessage.success('新增客户成功');
      }
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败');
    return false;
  }
};

// 删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条客户数据吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const response = await deleteuserAPI(id);
    if (response.code === 0) {
      ElMessage.success('删除客户成功');
      fetchUserList();
    }
  } catch (error) {
    if (error.type === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      console.error('删除客户失败:', error);
      ElMessage.error('删除客户失败');
    }
  }
};
</script>

<style lang="scss" scoped>
.user-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
}

.operation-bar {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
}

.pagination-bar {
  margin-top: 15px;
  text-align: right;
}

/* 可选：为电话输入框添加数字键盘样式提示 */
::v-deep(.el-input--tel) {
  input::-webkit-input-placeholder {
    color: #909399;
  }
}
</style>
